import React, { useEffect, useRef, useState } from 'react'
import { Row, Col, Card, List, Avatar, Drawer } from 'antd'
import axios from 'axios'
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import * as echarts from 'echarts';
import _ from 'lodash'

const { Meta } = Card;

function Home() {
    const [visible, setVisible] = useState(false);
    const [viewList, setViewList] = useState([])
    const [allList,setallList]=useState([])
    const [startList, setstartList] = useState([])
    const [pieChart, setpieChart] = useState(null)
    const barRef = useRef()
    const pieRef = useRef()
    const onClose = () => {
        setVisible(false);
    };

    useEffect(() => {
        axios.get("/news?publishState=2&expand=category&_sort=view&_order=desc&_limit=3").then(res => {

            setViewList(res.data)
        })
    }, [])
    useEffect(() => {
        axios.get("/news?publishState=2&expand=category&_sort=start&_order=desc&_limit=3").then(res => {

            setstartList(res.data)
        })
    }, [])
    useEffect(() => {
        axios.get("/news?publishState=2&expand=category").then(res => {
            renderBarView(_.groupBy(res.data, item => item.categoryId))
            // setallList(res.data)
        })
        return () => {
            window.resize = null
        }
    }, [])
    const renderBarView = (obj) => {
        var myChart = echarts.init(barRef.current);
        // 绘制图表
        myChart.setOption({
            title: {
                text: '新闻分类图示'
            },
            tooltip: {},
            xAxis: {
                data: Object.keys(obj),
                axisLable: {
                    rotate: "34"
                }
            },
            yAxis: {
                minInterval: 1
            },
            series: [
                {
                    name: '数量',
                    type: 'bar',
                    data: Object.values(obj).map(item => item.length)
                }
            ]
        });
        window.onresize = () => {
            myChart.resize()

        }
    }
    const renderPieView = () => {
        var currentList=allList.filter(item=>item.author===username)
        var groupObj=_.groupBy(currentList,item=>item.categoryId)
        console.log(groupObj);
        // var list=[]
        // for (var i  in groupObj){
        //     list.push({
                
        //     })
        // }

        var myChart

        console.log(pieRef.current);
        if(!pieChart){
            myChart = echarts.init(pieRef.current);
            setpieChart(myChart)
        }else{
            myChart=pieChart
        }
        var option;

        option = {
            title: {
                text: '当前用户新闻分类',
                left: 'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '发布数量',
                    type: 'pie',
                    radius: '50%',
                    data: [
                        { value: 1048, name: 'Search Engine' },
                        { value: 735, name: 'Direct' },
                        { value: 580, name: 'Email' },
                        { value: 484, name: 'Union Ads' },
                        { value: 300, name: 'Video Ads' }
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };

        option && myChart.setOption(option);

    }
    const { username, region, role: { roleName } } = JSON.parse(localStorage.getItem("token"))
    return (
        <div>

            <Row gutter={16}>
                <Col span={8}>
                    <Card title="用户最常浏览" bordered={true}>
                        <List
                            size="small"
                            dataSource={viewList}
                            renderItem={item => <List.Item><a href={`#/news-manage/preview/${item.id}`}>{item.title}</a></List.Item>}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card title="Card title" bordered={true}>
                        <List
                            size="small"
                            dataSource={startList}
                            renderItem={item => <List.Item><a href={`#/news-manage/preview/${item.id}`}>{item.title}</a></List.Item>}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card

                        cover={
                            <img
                                alt="example"
                                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
                            />
                        }
                        actions={[
                            <SettingOutlined key="setting" onClick={() =>{ 
                                setTimeout(() => {
                                    setVisible(true) 
                                    renderPieView()
                                }, 0);
                                }} />,
                            <EditOutlined key="edit" />,
                            <EllipsisOutlined key="ellipsis" />,
                        ]}
                    >
                        <Meta
                            avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
                            title={username}
                            description={
                                <div>
                                    <b>{region ? region : "全球"}</b>

                                    <span style={{ padding: 20 }}>{roleName}</span>
                                </div>
                            }
                        />
                    </Card>
                </Col>
            </Row>


            <div ref={barRef} style={{
                height: "600px",
                marginTop: "20px",

            }}>

            </div>
            <Drawer title="个人新闻分类"
                closable={true}
                width="500px"
                placement="right"
                onClose={onClose}
                visible={visible}>
                <div ref={pieRef}
                 style={{
                    height: "600px",
                    marginTop: "20px",

                }}>
                </div>
            </Drawer>
        </div>
    )
}

export default Home
